package com.zzyl.intercept;

import cn.hutool.core.text.AntPathMatcher;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.CacheConstant;
import com.zzyl.constant.Constants;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    // 路径匹配器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前请求是否是handler()
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        //获取token
        String token = request.getHeader(Constants.USER_TOKEN);

        // 判断token是否为空
        if (ObjectUtil.isEmpty(token)) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        //解析token
        Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
        if (ObjectUtil.isEmpty(claims)) {
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        // 获取用户数据
        String userJson = String.valueOf(claims.get("currentUser"));
        UserVo userVo = JSONUtil.toBean(userJson, UserVo.class);
        // 从Redis获取用户访问的列表
        String key = CacheConstant.PUBLIC_ACCESS_URLS + userVo.getId();
        String urlJson = redisTemplate.opsForValue().get(key);
        List<String> urlList = null;
        if (!ObjectUtil.isEmpty(urlJson)) {
            urlList = JSONUtil.toList(urlJson, String.class);
        }
        // 获取当前访问的路径
        String targetUrl = request.getMethod() + request.getRequestURI();
        // 验证用户当前访问路径是否 包含在 访问列表中
        for (String url : urlList) {
            if (antPathMatcher.match(url, targetUrl)) {
                // 如果匹配 把当前用户信息 存储到ThreadLocal中 放行
                UserThreadLocal.setSubject(userJson);
                return true;//放行
            }
        }
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.removeSubject();
    }
}
